/**
 * @file linked_stack.c
 * File implementing a generic LinkedStack data structure
 * @author Denis Ollier
 * @ingroup LinkedStack
 */

#include <linked_stack.h>
#include <stdlib.h>

linked_stack linked_stack_clone (linked_stack lkd_stk)
{
	linked_stack clone = NULL;
	return clone;
}

void linked_stack_dispose (linked_stack lkd_stk)
{
	struct cell* to_remove = (*lkd_stk);
	struct cell* next_to_remove;

	if ((*lkd_stk) != NULL)
	{
		while (to_remove->next != NULL)
		{
			next_to_remove = to_remove->next;
			free(to_remove);
			to_remove = next_to_remove;
		}
		free(lkd_stk);
	}
}

unsigned int linked_stack_is_empty (linked_stack lkd_stk)
{
	if (*lkd_stk == NULL)
		return 1;
	return 0;
}

linked_stack linked_stack_new (void)
{
	linked_stack new_linked_stack;

	new_linked_stack = (linked_stack) malloc(sizeof(struct cell*));
	(*new_linked_stack) = NULL;

	return new_linked_stack;
}

void* linked_stack_peek (linked_stack lkd_stk)
{
	if (*lkd_stk != NULL)
		return (*lkd_stk)->element;
	return NULL;
}

void* linked_stack_pop (linked_stack lkd_stk)
{
	struct cell* aux;
	void* top_linked_stack;

	if (*lkd_stk != NULL)
	{
		top_linked_stack = (*lkd_stk)->element;
		aux = (*lkd_stk);
		(*lkd_stk) = (*lkd_stk)->next;
		free(aux);
		return top_linked_stack;
	}
	return NULL;
}

unsigned int linked_stack_push (linked_stack lkd_stk, void* element)
{
	struct cell* new_cell = (struct cell*) malloc(sizeof(struct cell));
	if (new_cell != NULL)
	{
		new_cell->element = element;
		new_cell->next = (*lkd_stk);
		(*lkd_stk) = new_cell;
		return 1;
	}
	return 0;
}

int linked_stack_search (linked_stack lkd_stk, void* element)
{
	int index = 0;
	struct cell* aux = (*lkd_stk);

	while (aux != NULL)
	{
		if (aux->element == element)
			return index;
		aux = aux->next;
		index++;
	}

	return -1;
}
